<script lang="ts" setup>
import { computed, onMounted, ref, watch } from 'vue';

import {
  ElButton,
  ElCard,
  ElForm,
  ElFormItem,
  ElMessage,
  ElMessageBox,
  ElOption,
  ElPagination,
  ElSelect,
  ElTable,
  ElTableColumn,
} from 'element-plus';

// 导入API
import {
  exportDriverSubsidyData,
  getDriverSubsidyStatistics,
} from '#/api/subsidy';

// 筛选表单数据
const searchForm = ref({
  month: '', // 统计月份
});

// 日期快捷选项
const monthOptions = computed(() => {
  const currentYear = new Date().getFullYear();
  const currentMonth = new Date().getMonth() + 1;
  const months = [];

  // 生成最近12个月的选项
  for (let i = 0; i < 12; i++) {
    const year = currentMonth - i > 0 ? currentYear : currentYear - 1;
    const month = (currentMonth - i + 12) % 12 || 12;
    const monthStr = month < 10 ? `0${month}` : `${month}`;
    const yearMonth = `${year}-${monthStr}`;
    months.push({
      label: `${year}年${month}月`,
      value: yearMonth,
    });
  }

  // 设置默认值为当前月份
  if (!searchForm.value.month) {
    searchForm.value.month = `${currentYear}-${currentMonth < 10 ? `0${currentMonth}` : currentMonth}`;
  }

  return months;
});

// 表格数据
const tableData = ref<any[]>([]);
const loading = ref(false);

// 分页配置
const pagination = ref({
  currentPage: 1,
  pageSize: 20,
  total: 0,
});

// 每页条数选项
const pageSizeOptions = [15, 20, 25, 30];

// 排序配置
const sortConfig = ref({
  sortBy: '',
  sortOrder: '',
});

// 是否有数据
const hasData = computed(() => tableData.value.length > 0);

// // 监听筛选条件变化，更新数据
// watch(
//   () => searchForm.value.month,
//   () => {
//     if (searchForm.value.month) {
//       fetchDriverSubsidyData();
//     }
//   },
// );

// 监听分页和排序变化
watch(
  () => [
    pagination.value.currentPage,
    pagination.value.pageSize,
    sortConfig.value,
  ],
  () => {
    fetchDriverSubsidyData();
  },
  { deep: true },
);

// 获取司机补贴统计数据
const fetchDriverSubsidyData = async () => {
  if (!searchForm.value.month) {
    ElMessage.warning('请选择统计月份');
    return;
  }

  loading.value = true;

  try {
    const params = {
      month: searchForm.value.month,
      page: pagination.value.currentPage,
      pageSize: pagination.value.pageSize,
      sortBy: sortConfig.value.sortBy,
      sortOrder: sortConfig.value.sortOrder,
    };
    const response = await getDriverSubsidyStatistics(params);
    tableData.value = response.list || [];
    pagination.value.total = response.total || 0;

    // 如果没有数据，显示提示信息
    if (!hasData.value) {
      ElMessage.info('当前月份暂无补贴统计数据');
    }
  } catch (error) {
    console.error('获取司机补贴统计数据失败:', error);
    ElMessage.error('获取数据失败，请重试');
    tableData.value = [];
    pagination.value.total = 0;
  } finally {
    loading.value = false;
  }
};

// 处理查询
const handleSearch = () => {
  pagination.value.currentPage = 1; // 重置到第一页
  fetchDriverSubsidyData();
};

// 处理重置
const handleReset = () => {
  searchForm.value = {
    month: '',
  };
  pagination.value.currentPage = 1;
  sortConfig.value = {
    sortBy: '',
    sortOrder: '',
  };

  // 设置默认月份
  const currentYear = new Date().getFullYear();
  const currentMonth = new Date().getMonth() + 1;
  searchForm.value.month = `${currentYear}-${currentMonth < 10 ? `0${currentMonth}` : currentMonth}`;

  fetchDriverSubsidyData();
};

// 处理导出
const handleExport = async () => {
  if (!searchForm.value.month) {
    ElMessage.warning('请选择统计月份');
    return;
  }

  try {
    ElMessageBox.confirm(
      `确定要导出${searchForm.value.month}的司机补贴统计报表吗？`,
      '导出确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info',
      },
    ).then(async () => {
      const blob = await exportDriverSubsidyData({
        month: searchForm.value.month,
      });

      // 创建下载链接
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = `司机补贴统计报表_${searchForm.value.month.replace('-', '')}.xlsx`;

      document.body.append(link);
      link.click();
      link.remove();
      window.URL.revokeObjectURL(url);

      ElMessage.success('导出成功');
    });
  } catch (error) {
    console.error('导出司机补贴统计数据失败:', error);
    ElMessage.error('导出失败，请重试');
  }
};

// 处理分页变化
const handlePageChange = (page: number) => {
  pagination.value.currentPage = page;
};

// 处理每页条数变化
const handlePageSizeChange = (size: number) => {
  pagination.value.pageSize = size;
  pagination.value.currentPage = 1; // 切换条数时重置到第一页
};

// 处理排序
const handleSort = ({ prop, order }: { order: string; prop: string }) => {
  sortConfig.value.sortBy = prop;
  sortConfig.value.sortOrder =
    order === 'ascending' ? 'asc' : (order === 'descending' ? 'desc' : '');
};

// 详情弹框相关
const detailDialogVisible = ref(false);
const currentDetailRow = ref<any>(null);

// 处理查看详情
const handleViewDetail = (row: any) => {
  currentDetailRow.value = row;
  detailDialogVisible.value = true;
};

// 处理编辑补贴
const handleEditSubsidy = (row: any) => {
  ElMessageBox.alert(
    `
    <div class="text-left">
      <h4 class="text-lg font-semibold mb-3">编辑司机补贴</h4>
      <p class="text-gray-600 mb-3">司机: ${row.fullName} (${row.driverId})</p>
      <div class="space-y-3">
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-1">省内公里数</label>
          <input type="number" id="provinceMileage" value="${row.provinceMileage}"
                 class="w-full px-3 py-2 border border-gray-300 rounded-md" />
        </div>
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-1">省外公里数</label>
          <input type="number" id="outProvinceMileage" value="${row.outProvinceMileage}"
                 class="w-full px-3 py-2 border border-gray-300 rounded-md" />
        </div>
      </div>
      <div class="mt-4 text-center">
        <button onclick="alert('功能开发中，暂不支持编辑')"
                class="px-4 py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600">
          保存修改
        </button>
      </div>
    </div>
    `,
    '',
    {
      dangerouslyUseHTMLString: true,
      confirmButtonText: '关闭',
      customClass: 'edit-subsidy-dialog',
    },
  );
};

// 页面初始化
onMounted(() => {
  fetchDriverSubsidyData();
});
</script>

<template>
  <div class="min-h-screen bg-gray-50 p-5">
    <!-- 筛选区域 -->
    <ElCard class="mb-5 rounded-xl border-0 shadow-lg">
      <ElForm :model="searchForm" :inline="true" class="search-form">
        <div class="flex flex-wrap items-center gap-4">
          <ElFormItem
            label="统计月份"
            prop="month"
            class="min-w-[200px] flex-1"
          >
            <ElSelect
              v-model="searchForm.month"
              placeholder="请选择统计月份"
              clearable
              class="w-full"
            >
              <ElOption
                v-for="option in monthOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              />
            </ElSelect>
          </ElFormItem>

          <div class="flex gap-2">
            <ElButton type="primary" @click="handleSearch" class="px-4">
              查询
            </ElButton>
            <ElButton @click="handleReset" class="px-4"> 重置 </ElButton>
            <ElButton
              type="success"
              @click="handleExport"
              :disabled="!hasData"
              class="px-4"
            >
              导出
            </ElButton>
          </div>
        </div>
      </ElForm>
    </ElCard>

    <!-- 数据展示区 -->
    <ElCard class="rounded-xl border-0 shadow-lg">
      <div class="p-4">
        <div class="mb-4 flex items-center justify-between">
          <h3 class="text-lg font-semibold text-gray-800">司机补贴统计报表</h3>
          <span v-if="hasData" class="text-sm text-gray-600">
            共 {{ pagination.total }} 条记录
          </span>
        </div>

        <!-- 数据表格 -->
        <ElTable
          v-loading="loading"
          :data="tableData"
          class="subsidy-table overflow-hidden rounded-lg"
          :header-cell-style="{
            background: '#f8fafc',
            color: '#374151',
            fontWeight: '600',
            borderBottom: '2px solid #e5e7eb',
          }"
          :cell-style="{ borderBottom: '1px solid #f1f5f9' }"
          @sort-change="handleSort"
          :empty-text="
            searchForm.month ? '当前月份暂无补贴统计数据' : '请选择统计月份'
          "
        >
          <ElTableColumn
            prop="driverId"
            label="司机ID"
            sortable="custom"
            width="100"
            align="center"
          />
          <ElTableColumn
            prop="fullName"
            label="司机姓名"
            sortable="custom"
            width="120"
            align="center"
          />
          <ElTableColumn
            prop="phoneNumber"
            label="联系电话"
            sortable="custom"
            width="130"
            align="center"
          />
          <ElTableColumn
            prop="provinceMileage"
            label="当月省内公里数"
            sortable="custom"
            width="140"
            align="center"
          >
            <template #default="{ row }">
              {{ row.provinceMileage }} 公里
            </template>
          </ElTableColumn>
          <ElTableColumn
            prop="outProvinceMileage"
            label="当月省外公里数"
            sortable="custom"
            width="140"
            align="center"
          >
            <template #default="{ row }">
              {{ row.outProvinceMileage }} 公里
            </template>
          </ElTableColumn>
          <ElTableColumn
            prop="provinceSubsidyRate"
            label="省内补贴标准"
            sortable="custom"
            width="140"
            align="center"
          >
            <template #default="{ row }">
              {{ row.provinceSubsidyRate }} 元/公里
            </template>
          </ElTableColumn>
          <ElTableColumn
            prop="outProvinceSubsidyRate"
            label="省外补贴标准"
            sortable="custom"
            width="140"
            align="center"
          >
            <template #default="{ row }">
              {{ row.outProvinceSubsidyRate }} 元/公里
            </template>
          </ElTableColumn>
          <ElTableColumn
            prop="totalSubsidy"
            label="补贴总费用"
            sortable="custom"
            width="120"
            align="center"
          >
            <template #default="{ row }"> {{ row.totalSubsidy }} 元 </template>
          </ElTableColumn>
          <ElTableColumn
            prop="updateTime"
            label="数据更新时间"
            sortable="custom"
            width="160"
            align="center"
          />
          <ElTableColumn label="操作" width="120" align="center" fixed="right">
            <template #default="{ row }">
              <div class="flex justify-center gap-2">
                <ElButton
                  size="small"
                  type="primary"
                  text
                  @click="handleViewDetail(row)"
                >
                  查看详情
                </ElButton>
                <ElButton
                  size="small"
                  type="info"
                  text
                  @click="handleEditSubsidy(row)"
                >
                  编辑
                </ElButton>
              </div>
            </template>
          </ElTableColumn>
        </ElTable>

        <!-- 分页 -->
        <div v-if="hasData" class="mt-4 flex items-center justify-between">
          <div class="flex items-center gap-4">
            <span class="text-sm text-gray-600">
              显示
              {{ (pagination.currentPage - 1) * pagination.pageSize + 1 }} 到
              {{
                Math.min(
                  pagination.currentPage * pagination.pageSize,
                  pagination.total,
                )
              }}
              条，共 {{ pagination.total }} 条
            </span>
            <ElSelect
              v-model="pagination.pageSize"
              @change="handlePageSizeChange"
              class="w-20"
              size="small"
            >
              <ElOption
                v-for="size in pageSizeOptions"
                :key="size"
                :label="`${size} 条/页`"
                :value="size"
              />
            </ElSelect>
          </div>
          <ElPagination
            v-model:current-page="pagination.currentPage"
            :page-size="pagination.pageSize"
            :total="pagination.total"
            @current-change="handlePageChange"
            layout="prev, pager, next, jumper"
            background
          />
        </div>
      </div>
    </ElCard>
  </div>

  <!-- 详情弹框 -->
  <ElDialog
    v-model="detailDialogVisible"
    title="司机补贴详情"
    width="600px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <ElForm
      v-if="currentDetailRow"
      :model="currentDetailRow"
      label-width="120px"
      label-position="left"
      class="detail-form"
    >
      <ElFormItem label="司机ID">
        <span class="detail-value">{{ currentDetailRow.driverId }}</span>
      </ElFormItem>
      <ElFormItem label="司机姓名">
        <span class="detail-value">{{ currentDetailRow.fullName }}</span>
      </ElFormItem>
      <ElFormItem label="联系电话">
        <span class="detail-value">{{ currentDetailRow.phoneNumber }}</span>
      </ElFormItem>
      <ElFormItem label="当月省内公里数">
        <span class="detail-value">{{ currentDetailRow.provinceMileage }} 公里</span>
      </ElFormItem>
      <ElFormItem label="当月省外公里数">
        <span class="detail-value">{{ currentDetailRow.outProvinceMileage }} 公里</span>
      </ElFormItem>
      <ElFormItem label="省内补贴标准">
        <span class="detail-value">{{ currentDetailRow.provinceSubsidyRate }} 元/公里</span>
      </ElFormItem>
      <ElFormItem label="省外补贴标准">
        <span class="detail-value">{{ currentDetailRow.outProvinceSubsidyRate }} 元/公里</span>
      </ElFormItem>
      <ElFormItem label="补贴总费用">
        <span class="detail-value detail-total">{{ currentDetailRow.totalSubsidy }} 元</span>
      </ElFormItem>
      <ElFormItem label="数据更新时间">
        <span class="detail-value">{{ currentDetailRow.updateTime }}</span>
      </ElFormItem>
    </ElForm>
    <template #footer>
      <div class="dialog-footer">
        <ElButton @click="detailDialogVisible = false">关闭</ElButton>
      </div>
    </template>
  </ElDialog>
</template>

<style scoped>
/* 响应式优化 */
@media (max-width: 768px) {
  .flex-wrap {
    flex-direction: column;
    align-items: stretch;
  }

  .grid-cols-3 {
    grid-template-columns: repeat(1, 1fr);
  }

  .grid-cols-2 {
    grid-template-columns: 1fr;
  }
}

/* 自定义样式 */
:deep(.search-form .el-form-item__label) {
  font-size: 14px;
  font-weight: 500;
  color: #374151;
}

:deep(.el-input__wrapper) {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 2px 0 rgb(0 0 0 / 5%);
  transition: all 0.2s ease;
}

:deep(.el-select__wrapper) {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 2px 0 rgb(0 0 0 / 5%);
  transition: all 0.2s ease;
}

:deep(.el-button) {
  font-weight: 500;
  border-radius: 8px;
  transition: all 0.2s ease;
}

:deep(.el-card) {
  border: 1px solid #e5e7eb;
  border-radius: 12px;
  transition: all 0.3s ease;
}

:deep(.el-table) {
  overflow: hidden;
  border-radius: 8px;
}

:deep(.el-pagination) {
  justify-content: flex-end;
}

:deep(.subsidy-table .el-table__row:nth-child(even)) {
  background-color: #f9fafb;
}

:deep(.el-loading-mask) {
  background-color: rgb(255 255 255 / 80%);
}

/* 禁用导出按钮样式 */
:deep(.el-button:disabled) {
  color: #c0c4cc;
  cursor: not-allowed;
  background-color: #f5f7fa;
  border-color: #e4e7ed;
}
</style>
